package com.jzy.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jzy.constant.RedisConstant;
import com.jzy.dao.SetmealDao;
import com.jzy.entity.PageResult;
import com.jzy.entity.QueryPageBean;
import com.jzy.pojo.Setmeal;
import com.jzy.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 体检套餐服务
 */

@Service // Spring的
@com.alibaba.dubbo.config.annotation.Service(interfaceClass = SetmealService.class) // Dubbo的
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Resource
    private SetmealDao setmealDao;

    @Autowired
    private JedisPool jedisPool;//使用JedisPool操作Redis服务

    //静态页面生成相关
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")//从属性文件读取输出目录的路径
    private String outPutPath;

    @Override
    //新增套餐，同时关联检查组
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            //绑定套餐和检查组的多对多关系
            setSetmealAndCheckGroup(setmeal.getId(), checkgroupIds);
        }
        //将图片名称保存到Redis
        if (setmeal.getImg() != null) {
            savePic2Redis(setmeal.getImg());
        }

        //当添加套餐后重新生成静态页面(套餐列表页面、套餐详情页面)
        generateMobileStaticHtml();
    }


    /*分页查询*/
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        //获取参数
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> page = setmealDao.findByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /*删除套餐*/
    @Override
    public void deleteById(Integer setmealId) {
        //通过套餐ID查询与检查组中是否存在多对对关系
        long count = setmealDao.findCountBySetmealId(setmealId);
        if (count > 0) {//存在多对多关系
            //通过套餐id删除t_setmeal_checkgroup表中对应的值
            setmealDao.deleAssocication(setmealId);
        }
        setmealDao.deleteById(setmealId);
    }

    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.QueryById(id);
    }

    /*根据套餐ID查检查组包含的多个检查项*/
    @Override
    public List<Integer> finCheckItemIdsByCheckGroupId(Integer id) {
        return setmealDao.finCheckItemIdsByCheckGroupId(id);
    }

    /*编辑表单*/
    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //修改套餐基本信息，操作检查套餐t_setmeal表
        setmealDao.edit(setmeal);
        //清理当前检查套餐关联的检查检查组，操作中间关系表t_setmeal_checkgroup表
        setmealDao.deleAssocication(setmeal.getId());
        //重新建立当前检查套餐和检查组的关联关系
        setSetmealAndCheckGroup(setmeal.getId(), checkgroupIds);
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }


    // 根据套餐ID查询套餐详情（套餐基本信息、套餐对应的检查组信息、检查组对应的检查项信息）
    @Override
    public Setmeal findDetailById(int id) {
        return setmealDao.findDetailById(id);
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

    //绑定套餐和检查组的多对多关系
    private void setSetmealAndCheckGroup(Integer id, Integer[] checkgroupIds) {
        for (Integer checkgroupId : checkgroupIds) {
            Map<String, Integer> map = new HashMap<>();
            map.put("setmeal_id", id);
            map.put("checkgroup_id", checkgroupId);
            setmealDao.setSetmealAndCheckGroup(map);
        }
    }

    //将图片名称保存到Redis
    private void savePic2Redis(String pic) {
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, pic);
    }

    //用于生成静态页面
//生成静态页面
    public void generateMobileStaticHtml() {
        //准备模板文件中所需的数据
        List<Setmeal> setmealList = this.findAll();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);
        //生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(setmealList);
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("setmealList", setmealList);
        this.generateHtml("mobile_setmeal.ftl", "m_setmeal.html", dataMap);
    }

    //生成套餐详情静态页面（多个）
    public void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("setmeal", this.findDetailById(setmeal.getId()));
            this.generateHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", dataMap);
        }
    }

    public void generateHtml(String templateName, String htmlPageName, Map<String, Object> dataMap) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            // 加载模版文件
            Template template = configuration.getTemplate(templateName);
            // 生成数据
            File docFile = new File(outPutPath + "\\" + htmlPageName);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
            // 输出文件
            template.process(dataMap, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != out) {
                    out.flush();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

}
